#include "comm.hpp"
#include <sys/wait.h>

static void getMessage(int fd)
{
    char buffer[SIZE];
    while (true)
    {
        memset(buffer, 0, sizeof(buffer));
        ssize_t s = read(fd, buffer, sizeof(buffer) - 1);
        if (s > 0)
        {
            cout << "[" << getpid() << "]" << "client say> " << buffer << endl;
        }
        else if (s == 0)
        {
            cerr << "[" << getpid() << "]" << "read end of file, client quit, server quit, too" << endl;
            break;
        }
        else
        {
            perror("read");
            break;
        }
    }
}
int main()
{
    if (mkfifo(ipcPath.c_str(), MODE) < 0)
    {
        perror("mkfifo");
        exit(1);
    }
    Log("create fifo success", Debug) << " step 1" << endl;
    int fd = open(ipcPath.c_str(), O_RDONLY);
    if (fd < 0)
    {
        perror("open");
        exit(2);
    }
    Log("open fifo success", Debug) << " step 2" << endl;

    int nums = 3;
    for (int i = 0; i < nums; ++i)
    {
        pid_t id = fork();
        if (id == 0)
        {
            getMessage(fd);
            exit(3);
        }
    }
    for (int i = 0; i < nums; ++i)
    {
        waitpid(-1, nullptr, 0);
    }
    close(fd);
    Log("server quit success", Debug) << " step 3" << endl;
    unlink(ipcPath.c_str());
    Log("unlink fifo success", Debug) << " step 4" << endl;

    return 0;
}